

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Logging Cookbook &mdash; Python v2.7.8 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.7.8',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.7.8 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.7.8 documentation" href="../index.html" />
    <link rel="up" title="Python HOWTOs" href="index.html" />
    <link rel="next" title="Regular Expression HOWTO" href="regex.html" />
    <link rel="prev" title="Logging HOWTO" href="logging.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head>
  <body>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="regex.html" title="Regular Expression HOWTO"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="logging.html" title="Logging HOWTO"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="http://www.python.org/">Python</a> &raquo;</li>
        <li>
          <a href="../index.html">Python v2.7.8 documentation</a> &raquo;
        </li>

          <li><a href="index.html" accesskey="U">Python HOWTOs</a> &raquo;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="logging-cookbook">
<span id="id1"></span><h1>Logging Cookbook<a class="headerlink" href="#logging-cookbook" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Author:</th><td class="field-body">Vinay Sajip &lt;vinay_sajip at red-dove dot com&gt;</td>
</tr>
</tbody>
</table>
<p>This page contains a number of recipes related to logging, which have been found
useful in the past.</p>
<div class="section" id="using-logging-in-multiple-modules">
<h2>Using logging in multiple modules<a class="headerlink" href="#using-logging-in-multiple-modules" title="Permalink to this headline">¶</a></h2>
<p>Multiple calls to <tt class="docutils literal"><span class="pre">logging.getLogger('someLogger')</span></tt> return a reference to the
same logger object.  This is true not only within the same module, but also
across modules as long as it is in the same Python interpreter process.  It is
true for references to the same object; additionally, application code can
define and configure a parent logger in one module and create (but not
configure) a child logger in a separate module, and all logger calls to the
child will pass up to the parent.  Here is a main module:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">auxiliary_module</span>

<span class="c"># create logger with &#39;spam_application&#39;</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;spam_application&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="c"># create file handler which logs even debug messages</span>
<span class="n">fh</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="s">&#39;spam.log&#39;</span><span class="p">)</span>
<span class="n">fh</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="c"># create console handler with a higher log level</span>
<span class="n">ch</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">()</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">ERROR</span><span class="p">)</span>
<span class="c"># create formatter and add it to the handlers</span>
<span class="n">formatter</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">(</span><span class="s">&#39;</span><span class="si">%(asctime)s</span><span class="s"> - </span><span class="si">%(name)s</span><span class="s"> - </span><span class="si">%(levelname)s</span><span class="s"> - </span><span class="si">%(message)s</span><span class="s">&#39;</span><span class="p">)</span>
<span class="n">fh</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
<span class="c"># add the handlers to the logger</span>
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">fh</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">ch</span><span class="p">)</span>

<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;creating an instance of auxiliary_module.Auxiliary&#39;</span><span class="p">)</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">auxiliary_module</span><span class="o">.</span><span class="n">Auxiliary</span><span class="p">()</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;created an instance of auxiliary_module.Auxiliary&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;calling auxiliary_module.Auxiliary.do_something&#39;</span><span class="p">)</span>
<span class="n">a</span><span class="o">.</span><span class="n">do_something</span><span class="p">()</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;finished auxiliary_module.Auxiliary.do_something&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;calling auxiliary_module.some_function()&#39;</span><span class="p">)</span>
<span class="n">auxiliary_module</span><span class="o">.</span><span class="n">some_function</span><span class="p">()</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;done with auxiliary_module.some_function()&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Here is the auxiliary module:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span>

<span class="c"># create logger</span>
<span class="n">module_logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;spam_application.auxiliary&#39;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Auxiliary</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;spam_application.auxiliary.Auxiliary&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;creating an instance of Auxiliary&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">do_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;doing something&#39;</span><span class="p">)</span>
        <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">+</span> <span class="mi">1</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;done doing something&#39;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">some_function</span><span class="p">():</span>
    <span class="n">module_logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;received a call to &quot;some_function&quot;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The output looks like this:</p>
<div class="highlight-python"><pre>2005-03-23 23:47:11,663 - spam_application - INFO -
   creating an instance of auxiliary_module.Auxiliary
2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
   creating an instance of Auxiliary
2005-03-23 23:47:11,665 - spam_application - INFO -
   created an instance of auxiliary_module.Auxiliary
2005-03-23 23:47:11,668 - spam_application - INFO -
   calling auxiliary_module.Auxiliary.do_something
2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
   doing something
2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
   done doing something
2005-03-23 23:47:11,670 - spam_application - INFO -
   finished auxiliary_module.Auxiliary.do_something
2005-03-23 23:47:11,671 - spam_application - INFO -
   calling auxiliary_module.some_function()
2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
   received a call to 'some_function'
2005-03-23 23:47:11,673 - spam_application - INFO -
   done with auxiliary_module.some_function()</pre>
</div>
</div>
<div class="section" id="multiple-handlers-and-formatters">
<h2>Multiple handlers and formatters<a class="headerlink" href="#multiple-handlers-and-formatters" title="Permalink to this headline">¶</a></h2>
<p>Loggers are plain Python objects.  The <a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><tt class="xref py py-meth docutils literal"><span class="pre">addHandler()</span></tt></a> method has no
minimum or maximum quota for the number of handlers you may add.  Sometimes it
will be beneficial for an application to log all messages of all severities to a
text file while simultaneously logging errors or above to the console.  To set
this up, simply configure the appropriate handlers.  The logging calls in the
application code will remain unchanged.  Here is a slight modification to the
previous simple module-based configuration example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span>

<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;simple_example&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="c"># create file handler which logs even debug messages</span>
<span class="n">fh</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="s">&#39;spam.log&#39;</span><span class="p">)</span>
<span class="n">fh</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="c"># create console handler with a higher log level</span>
<span class="n">ch</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">()</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">ERROR</span><span class="p">)</span>
<span class="c"># create formatter and add it to the handlers</span>
<span class="n">formatter</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">(</span><span class="s">&#39;</span><span class="si">%(asctime)s</span><span class="s"> - </span><span class="si">%(name)s</span><span class="s"> - </span><span class="si">%(levelname)s</span><span class="s"> - </span><span class="si">%(message)s</span><span class="s">&#39;</span><span class="p">)</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
<span class="n">fh</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
<span class="c"># add the handlers to logger</span>
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">ch</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">fh</span><span class="p">)</span>

<span class="c"># &#39;application&#39; code</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">&#39;debug message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;info message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s">&#39;warn message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">&#39;error message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s">&#39;critical message&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Notice that the &#8216;application&#8217; code does not care about multiple handlers.  All
that changed was the addition and configuration of a new handler named <em>fh</em>.</p>
<p>The ability to create new handlers with higher- or lower-severity filters can be
very helpful when writing and testing an application.  Instead of using many
<tt class="docutils literal"><span class="pre">print</span></tt> statements for debugging, use <tt class="docutils literal"><span class="pre">logger.debug</span></tt>: Unlike the print
statements, which you will have to delete or comment out later, the logger.debug
statements can remain intact in the source code and remain dormant until you
need them again.  At that time, the only change that needs to happen is to
modify the severity level of the logger and/or handler to debug.</p>
</div>
<div class="section" id="logging-to-multiple-destinations">
<span id="multiple-destinations"></span><h2>Logging to multiple destinations<a class="headerlink" href="#logging-to-multiple-destinations" title="Permalink to this headline">¶</a></h2>
<p>Let&#8217;s say you want to log to console and file with different message formats and
in differing circumstances. Say you want to log messages with levels of DEBUG
and higher to file, and those messages at level INFO and higher to the console.
Let&#8217;s also assume that the file should contain timestamps, but the console
messages should not. Here&#8217;s how you can achieve this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span>

<span class="c"># set up logging to file - see previous section for more details</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">,</span>
                    <span class="n">format</span><span class="o">=</span><span class="s">&#39;</span><span class="si">%(asctime)s</span><span class="s"> </span><span class="si">%(name)-12s</span><span class="s"> </span><span class="si">%(levelname)-8s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">&#39;</span><span class="p">,</span>
                    <span class="n">datefmt</span><span class="o">=</span><span class="s">&#39;%m-</span><span class="si">%d</span><span class="s"> %H:%M&#39;</span><span class="p">,</span>
                    <span class="n">filename</span><span class="o">=</span><span class="s">&#39;/temp/myapp.log&#39;</span><span class="p">,</span>
                    <span class="n">filemode</span><span class="o">=</span><span class="s">&#39;w&#39;</span><span class="p">)</span>
<span class="c"># define a Handler which writes INFO messages or higher to the sys.stderr</span>
<span class="n">console</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">()</span>
<span class="n">console</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">)</span>
<span class="c"># set a format which is simpler for console use</span>
<span class="n">formatter</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">(</span><span class="s">&#39;</span><span class="si">%(name)-12s</span><span class="s">: </span><span class="si">%(levelname)-8s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">&#39;</span><span class="p">)</span>
<span class="c"># tell the handler to use this format</span>
<span class="n">console</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
<span class="c"># add the handler to the root logger</span>
<span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">console</span><span class="p">)</span>

<span class="c"># Now, we can log to the root logger, or any other logger. First the root...</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;Jackdaws love my big sphinx of quartz.&#39;</span><span class="p">)</span>

<span class="c"># Now, define a couple of other loggers which might represent areas in your</span>
<span class="c"># application:</span>

<span class="n">logger1</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;myapp.area1&#39;</span><span class="p">)</span>
<span class="n">logger2</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;myapp.area2&#39;</span><span class="p">)</span>

<span class="n">logger1</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">&#39;Quick zephyrs blow, vexing daft Jim.&#39;</span><span class="p">)</span>
<span class="n">logger1</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;How quickly daft jumping zebras vex.&#39;</span><span class="p">)</span>
<span class="n">logger2</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">&#39;Jail zesty vixen who grabbed pay from quack.&#39;</span><span class="p">)</span>
<span class="n">logger2</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">&#39;The five boxing wizards jump quickly.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>When you run this, on the console you will see</p>
<div class="highlight-python"><pre>root        : INFO     Jackdaws love my big sphinx of quartz.
myapp.area1 : INFO     How quickly daft jumping zebras vex.
myapp.area2 : WARNING  Jail zesty vixen who grabbed pay from quack.
myapp.area2 : ERROR    The five boxing wizards jump quickly.</pre>
</div>
<p>and in the file you will see something like</p>
<div class="highlight-python"><pre>10-22 22:19 root         INFO     Jackdaws love my big sphinx of quartz.
10-22 22:19 myapp.area1  DEBUG    Quick zephyrs blow, vexing daft Jim.
10-22 22:19 myapp.area1  INFO     How quickly daft jumping zebras vex.
10-22 22:19 myapp.area2  WARNING  Jail zesty vixen who grabbed pay from quack.
10-22 22:19 myapp.area2  ERROR    The five boxing wizards jump quickly.</pre>
</div>
<p>As you can see, the DEBUG message only shows up in the file. The other messages
are sent to both destinations.</p>
<p>This example uses console and file handlers, but you can use any number and
combination of handlers you choose.</p>
</div>
<div class="section" id="configuration-server-example">
<h2>Configuration server example<a class="headerlink" href="#configuration-server-example" title="Permalink to this headline">¶</a></h2>
<p>Here is an example of a module using the logging configuration server:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.config</span>
<span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="c"># read initial config file</span>
<span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">fileConfig</span><span class="p">(</span><span class="s">&#39;logging.conf&#39;</span><span class="p">)</span>

<span class="c"># create and start listener on port 9999</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="mi">9999</span><span class="p">)</span>
<span class="n">t</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;simpleExample&#39;</span><span class="p">)</span>

<span class="k">try</span><span class="p">:</span>
    <span class="c"># loop through logging calls to see the difference</span>
    <span class="c"># new configurations make, until Ctrl+C is pressed</span>
    <span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">&#39;debug message&#39;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;info message&#39;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s">&#39;warn message&#39;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">&#39;error message&#39;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s">&#39;critical message&#39;</span><span class="p">)</span>
        <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">KeyboardInterrupt</span><span class="p">:</span>
    <span class="c"># cleanup</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">stopListening</span><span class="p">()</span>
    <span class="n">t</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
</pre></div>
</div>
<p>And here is a script that takes a filename and sends that file to the server,
properly preceded with the binary-encoded length, as the new logging
configuration:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c">#!/usr/bin/env python</span>
<span class="kn">import</span> <span class="nn">socket</span><span class="o">,</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">struct</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="s">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">data_to_send</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>

<span class="n">HOST</span> <span class="o">=</span> <span class="s">&#39;localhost&#39;</span>
<span class="n">PORT</span> <span class="o">=</span> <span class="mi">9999</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s">&#39;connecting...&#39;</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">connect</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">))</span>
<span class="k">print</span><span class="p">(</span><span class="s">&#39;sending config...&#39;</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="s">&#39;&gt;L&#39;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">data_to_send</span><span class="p">)))</span>
<span class="n">s</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">data_to_send</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="k">print</span><span class="p">(</span><span class="s">&#39;complete&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="sending-and-receiving-logging-events-across-a-network">
<span id="network-logging"></span><h2>Sending and receiving logging events across a network<a class="headerlink" href="#sending-and-receiving-logging-events-across-a-network" title="Permalink to this headline">¶</a></h2>
<p>Let&#8217;s say you want to send logging events across a network, and handle them at
the receiving end. A simple way of doing this is attaching a
<tt class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></tt> instance to the root logger at the sending end:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span><span class="o">,</span> <span class="nn">logging.handlers</span>

<span class="n">rootLogger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;&#39;</span><span class="p">)</span>
<span class="n">rootLogger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="n">socketHandler</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">SocketHandler</span><span class="p">(</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span>
                    <span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">DEFAULT_TCP_LOGGING_PORT</span><span class="p">)</span>
<span class="c"># don&#39;t bother with a formatter, since a socket handler sends the event as</span>
<span class="c"># an unformatted pickle</span>
<span class="n">rootLogger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">socketHandler</span><span class="p">)</span>

<span class="c"># Now, we can log to the root logger, or any other logger. First the root...</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;Jackdaws love my big sphinx of quartz.&#39;</span><span class="p">)</span>

<span class="c"># Now, define a couple of other loggers which might represent areas in your</span>
<span class="c"># application:</span>

<span class="n">logger1</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;myapp.area1&#39;</span><span class="p">)</span>
<span class="n">logger2</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;myapp.area2&#39;</span><span class="p">)</span>

<span class="n">logger1</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">&#39;Quick zephyrs blow, vexing daft Jim.&#39;</span><span class="p">)</span>
<span class="n">logger1</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;How quickly daft jumping zebras vex.&#39;</span><span class="p">)</span>
<span class="n">logger2</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s">&#39;Jail zesty vixen who grabbed pay from quack.&#39;</span><span class="p">)</span>
<span class="n">logger2</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">&#39;The five boxing wizards jump quickly.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>At the receiving end, you can set up a receiver using the <a class="reference internal" href="../library/socketserver.html#module-SocketServer" title="SocketServer: A framework for network servers."><tt class="xref py py-mod docutils literal"><span class="pre">SocketServer</span></tt></a>
module. Here is a basic working example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">pickle</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.handlers</span>
<span class="kn">import</span> <span class="nn">SocketServer</span>
<span class="kn">import</span> <span class="nn">struct</span>


<span class="k">class</span> <span class="nc">LogRecordStreamHandler</span><span class="p">(</span><span class="n">SocketServer</span><span class="o">.</span><span class="n">StreamRequestHandler</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Handler for a streaming logging request.</span>

<span class="sd">    This basically logs the record using whatever logging policy is</span>
<span class="sd">    configured locally.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">handle</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Handle multiple requests - each expected to be a 4-byte length,</span>
<span class="sd">        followed by the LogRecord in pickle format. Logs the record</span>
<span class="sd">        according to whatever policy is configured locally.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
            <span class="n">chunk</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
            <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">4</span><span class="p">:</span>
                <span class="k">break</span>
            <span class="n">slen</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="s">&#39;&gt;L&#39;</span><span class="p">,</span> <span class="n">chunk</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
            <span class="n">chunk</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="n">slen</span><span class="p">)</span>
            <span class="k">while</span> <span class="nb">len</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">slen</span><span class="p">:</span>
                <span class="n">chunk</span> <span class="o">=</span> <span class="n">chunk</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="n">slen</span> <span class="o">-</span> <span class="nb">len</span><span class="p">(</span><span class="n">chunk</span><span class="p">))</span>
            <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">unPickle</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>
            <span class="n">record</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">makeLogRecord</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">handleLogRecord</span><span class="p">(</span><span class="n">record</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">unPickle</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">pickle</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">handleLogRecord</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">record</span><span class="p">):</span>
        <span class="c"># if a name is specified, we use the named logger rather than the one</span>
        <span class="c"># implied by the record.</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">server</span><span class="o">.</span><span class="n">logname</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
            <span class="n">name</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">server</span><span class="o">.</span><span class="n">logname</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">name</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="n">name</span>
        <span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
        <span class="c"># N.B. EVERY record gets logged. This is because Logger.handle</span>
        <span class="c"># is normally called AFTER logger-level filtering. If you want</span>
        <span class="c"># to do filtering, do it at the client end to save wasting</span>
        <span class="c"># cycles and network bandwidth!</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">handle</span><span class="p">(</span><span class="n">record</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">LogRecordSocketReceiver</span><span class="p">(</span><span class="n">SocketServer</span><span class="o">.</span><span class="n">ThreadingTCPServer</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Simple TCP socket-based logging receiver suitable for testing.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="n">allow_reuse_address</span> <span class="o">=</span> <span class="mi">1</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="s">&#39;localhost&#39;</span><span class="p">,</span>
                 <span class="n">port</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">DEFAULT_TCP_LOGGING_PORT</span><span class="p">,</span>
                 <span class="n">handler</span><span class="o">=</span><span class="n">LogRecordStreamHandler</span><span class="p">):</span>
        <span class="n">SocketServer</span><span class="o">.</span><span class="n">ThreadingTCPServer</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="p">(</span><span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">),</span> <span class="n">handler</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">abort</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">timeout</span> <span class="o">=</span> <span class="mi">1</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">logname</span> <span class="o">=</span> <span class="bp">None</span>

    <span class="k">def</span> <span class="nf">serve_until_stopped</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="kn">import</span> <span class="nn">select</span>
        <span class="n">abort</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="k">while</span> <span class="ow">not</span> <span class="n">abort</span><span class="p">:</span>
            <span class="n">rd</span><span class="p">,</span> <span class="n">wr</span><span class="p">,</span> <span class="n">ex</span> <span class="o">=</span> <span class="n">select</span><span class="o">.</span><span class="n">select</span><span class="p">([</span><span class="bp">self</span><span class="o">.</span><span class="n">socket</span><span class="o">.</span><span class="n">fileno</span><span class="p">()],</span>
                                       <span class="p">[],</span> <span class="p">[],</span>
                                       <span class="bp">self</span><span class="o">.</span><span class="n">timeout</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">rd</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">handle_request</span><span class="p">()</span>
            <span class="n">abort</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">abort</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span>
        <span class="n">format</span><span class="o">=</span><span class="s">&#39;</span><span class="si">%(relativeCreated)5d</span><span class="s"> </span><span class="si">%(name)-15s</span><span class="s"> </span><span class="si">%(levelname)-8s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">&#39;</span><span class="p">)</span>
    <span class="n">tcpserver</span> <span class="o">=</span> <span class="n">LogRecordSocketReceiver</span><span class="p">()</span>
    <span class="k">print</span><span class="p">(</span><span class="s">&#39;About to start TCP server...&#39;</span><span class="p">)</span>
    <span class="n">tcpserver</span><span class="o">.</span><span class="n">serve_until_stopped</span><span class="p">()</span>

<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>First run the server, and then the client. On the client side, nothing is
printed on the console; on the server side, you should see something like:</p>
<div class="highlight-python"><pre>About to start TCP server...
   59 root            INFO     Jackdaws love my big sphinx of quartz.
   59 myapp.area1     DEBUG    Quick zephyrs blow, vexing daft Jim.
   69 myapp.area1     INFO     How quickly daft jumping zebras vex.
   69 myapp.area2     WARNING  Jail zesty vixen who grabbed pay from quack.
   69 myapp.area2     ERROR    The five boxing wizards jump quickly.</pre>
</div>
<p>Note that there are some security issues with pickle in some scenarios. If
these affect you, you can use an alternative serialization scheme by overriding
the <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SocketHandler.makePickle" title="logging.handlers.SocketHandler.makePickle"><tt class="xref py py-meth docutils literal"><span class="pre">makePickle()</span></tt></a> method and implementing your
alternative there, as well as adapting the above script to use your alternative
serialization.</p>
</div>
<div class="section" id="adding-contextual-information-to-your-logging-output">
<span id="context-info"></span><h2>Adding contextual information to your logging output<a class="headerlink" href="#adding-contextual-information-to-your-logging-output" title="Permalink to this headline">¶</a></h2>
<p>Sometimes you want logging output to contain contextual information in
addition to the parameters passed to the logging call. For example, in a
networked application, it may be desirable to log client-specific information
in the log (e.g. remote client&#8217;s username, or IP address). Although you could
use the <em>extra</em> parameter to achieve this, it&#8217;s not always convenient to pass
the information in this way. While it might be tempting to create
<a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> instances on a per-connection basis, this is not a good idea
because these instances are not garbage collected. While this is not a problem
in practice, when the number of <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> instances is dependent on the
level of granularity you want to use in logging an application, it could
be hard to manage if the number of <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> instances becomes
effectively unbounded.</p>
<div class="section" id="using-loggeradapters-to-impart-contextual-information">
<h3>Using LoggerAdapters to impart contextual information<a class="headerlink" href="#using-loggeradapters-to-impart-contextual-information" title="Permalink to this headline">¶</a></h3>
<p>An easy way in which you can pass contextual information to be output along
with logging event information is to use the <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a> class.
This class is designed to look like a <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a>, so that you can call
<a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><tt class="xref py py-meth docutils literal"><span class="pre">debug()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><tt class="xref py py-meth docutils literal"><span class="pre">info()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><tt class="xref py py-meth docutils literal"><span class="pre">warning()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><tt class="xref py py-meth docutils literal"><span class="pre">error()</span></tt></a>,
<a class="reference internal" href="../library/logging.html#logging.exception" title="logging.exception"><tt class="xref py py-meth docutils literal"><span class="pre">exception()</span></tt></a>, <a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><tt class="xref py py-meth docutils literal"><span class="pre">critical()</span></tt></a> and <a class="reference internal" href="../library/logging.html#logging.log" title="logging.log"><tt class="xref py py-meth docutils literal"><span class="pre">log()</span></tt></a>. These methods have the
same signatures as their counterparts in <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a>, so you can use the
two types of instances interchangeably.</p>
<p>When you create an instance of <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a>, you pass it a
<a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> instance and a dict-like object which contains your contextual
information. When you call one of the logging methods on an instance of
<a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a>, it delegates the call to the underlying instance of
<a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><tt class="xref py py-class docutils literal"><span class="pre">Logger</span></tt></a> passed to its constructor, and arranges to pass the contextual
information in the delegated call. Here&#8217;s a snippet from the code of
<a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">debug</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Delegate a debug call to the underlying logger, after adding</span>
<span class="sd">    contextual information from this adapter instance.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">msg</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">process</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter.process" title="logging.LoggerAdapter.process"><tt class="xref py py-meth docutils literal"><span class="pre">process()</span></tt></a> method of <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a> is where the
contextual information is added to the logging output. It&#8217;s passed the message
and keyword arguments of the logging call, and it passes back (potentially)
modified versions of these to use in the call to the underlying logger. The
default implementation of this method leaves the message alone, but inserts
an &#8216;extra&#8217; key in the keyword argument whose value is the dict-like object
passed to the constructor. Of course, if you had passed an &#8216;extra&#8217; keyword
argument in the call to the adapter, it will be silently overwritten.</p>
<p>The advantage of using &#8216;extra&#8217; is that the values in the dict-like object are
merged into the <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><tt class="xref py py-class docutils literal"><span class="pre">LogRecord</span></tt></a> instance&#8217;s __dict__, allowing you to use
customized strings with your <a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> instances which know about
the keys of the dict-like object. If you need a different method, e.g. if you
want to prepend or append the contextual information to the message string,
you just need to subclass <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a> and override
<a class="reference internal" href="../library/logging.html#logging.LoggerAdapter.process" title="logging.LoggerAdapter.process"><tt class="xref py py-meth docutils literal"><span class="pre">process()</span></tt></a> to do what you need. Here is a simple example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">CustomAdapter</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">LoggerAdapter</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    This example adapter expects the passed in dict-like object to have a</span>
<span class="sd">    &#39;connid&#39; key, whose value in brackets is prepended to the log message.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">def</span> <span class="nf">process</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">):</span>
        <span class="k">return</span> <span class="s">&#39;[</span><span class="si">%s</span><span class="s">] </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">extra</span><span class="p">[</span><span class="s">&#39;connid&#39;</span><span class="p">],</span> <span class="n">msg</span><span class="p">),</span> <span class="n">kwargs</span>
</pre></div>
</div>
<p>which you can use like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="n">__name__</span><span class="p">)</span>
<span class="n">adapter</span> <span class="o">=</span> <span class="n">CustomAdapter</span><span class="p">(</span><span class="n">logger</span><span class="p">,</span> <span class="p">{</span><span class="s">&#39;connid&#39;</span><span class="p">:</span> <span class="n">some_conn_id</span><span class="p">})</span>
</pre></div>
</div>
<p>Then any events that you log to the adapter will have the value of
<tt class="docutils literal"><span class="pre">some_conn_id</span></tt> prepended to the log messages.</p>
<div class="section" id="using-objects-other-than-dicts-to-pass-contextual-information">
<h4>Using objects other than dicts to pass contextual information<a class="headerlink" href="#using-objects-other-than-dicts-to-pass-contextual-information" title="Permalink to this headline">¶</a></h4>
<p>You don&#8217;t need to pass an actual dict to a <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><tt class="xref py py-class docutils literal"><span class="pre">LoggerAdapter</span></tt></a> - you could
pass an instance of a class which implements <tt class="docutils literal"><span class="pre">__getitem__</span></tt> and <tt class="docutils literal"><span class="pre">__iter__</span></tt> so
that it looks like a dict to logging. This would be useful if you want to
generate values dynamically (whereas the values in a dict would be constant).</p>
</div>
</div>
<div class="section" id="using-filters-to-impart-contextual-information">
<span id="filters-contextual"></span><h3>Using Filters to impart contextual information<a class="headerlink" href="#using-filters-to-impart-contextual-information" title="Permalink to this headline">¶</a></h3>
<p>You can also add contextual information to log output using a user-defined
<a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><tt class="xref py py-class docutils literal"><span class="pre">Filter</span></tt></a>. <tt class="docutils literal"><span class="pre">Filter</span></tt> instances are allowed to modify the <tt class="docutils literal"><span class="pre">LogRecords</span></tt>
passed to them, including adding additional attributes which can then be output
using a suitable format string, or if needed a custom <a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a>.</p>
<p>For example in a web application, the request being processed (or at least,
the interesting parts of it) can be stored in a threadlocal
(<a class="reference internal" href="../library/threading.html#threading.local" title="threading.local"><tt class="xref py py-class docutils literal"><span class="pre">threading.local</span></tt></a>) variable, and then accessed from a <tt class="docutils literal"><span class="pre">Filter</span></tt> to
add, say, information from the request - say, the remote IP address and remote
user&#8217;s username - to the <tt class="docutils literal"><span class="pre">LogRecord</span></tt>, using the attribute names &#8216;ip&#8217; and
&#8216;user&#8217; as in the <tt class="docutils literal"><span class="pre">LoggerAdapter</span></tt> example above. In that case, the same format
string can be used to get similar output to that shown above. Here&#8217;s an example
script:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">from</span> <span class="nn">random</span> <span class="kn">import</span> <span class="n">choice</span>

<span class="k">class</span> <span class="nc">ContextFilter</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">Filter</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    This is a filter which injects contextual information into the log.</span>

<span class="sd">    Rather than use actual contextual information, we just use random</span>
<span class="sd">    data in this demo.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="n">USERS</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;jim&#39;</span><span class="p">,</span> <span class="s">&#39;fred&#39;</span><span class="p">,</span> <span class="s">&#39;sheila&#39;</span><span class="p">]</span>
    <span class="n">IPS</span> <span class="o">=</span> <span class="p">[</span><span class="s">&#39;123.231.231.123&#39;</span><span class="p">,</span> <span class="s">&#39;127.0.0.1&#39;</span><span class="p">,</span> <span class="s">&#39;192.168.0.1&#39;</span><span class="p">]</span>

    <span class="k">def</span> <span class="nf">filter</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">record</span><span class="p">):</span>

        <span class="n">record</span><span class="o">.</span><span class="n">ip</span> <span class="o">=</span> <span class="n">choice</span><span class="p">(</span><span class="n">ContextFilter</span><span class="o">.</span><span class="n">IPS</span><span class="p">)</span>
        <span class="n">record</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="n">choice</span><span class="p">(</span><span class="n">ContextFilter</span><span class="o">.</span><span class="n">USERS</span><span class="p">)</span>
        <span class="k">return</span> <span class="bp">True</span>

<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&#39;__main__&#39;</span><span class="p">:</span>
   <span class="n">levels</span> <span class="o">=</span> <span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">,</span> <span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">,</span> <span class="n">logging</span><span class="o">.</span><span class="n">WARNING</span><span class="p">,</span> <span class="n">logging</span><span class="o">.</span><span class="n">ERROR</span><span class="p">,</span> <span class="n">logging</span><span class="o">.</span><span class="n">CRITICAL</span><span class="p">)</span>
   <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">,</span>
                       <span class="n">format</span><span class="o">=</span><span class="s">&#39;</span><span class="si">%(asctime)-15s</span><span class="s"> </span><span class="si">%(name)-5s</span><span class="s"> </span><span class="si">%(levelname)-8s</span><span class="s"> IP: </span><span class="si">%(ip)-15s</span><span class="s"> User: </span><span class="si">%(user)-8s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">&#39;</span><span class="p">)</span>
   <span class="n">a1</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;a.b.c&#39;</span><span class="p">)</span>
   <span class="n">a2</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;d.e.f&#39;</span><span class="p">)</span>

   <span class="n">f</span> <span class="o">=</span> <span class="n">ContextFilter</span><span class="p">()</span>
   <span class="n">a1</span><span class="o">.</span><span class="n">addFilter</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
   <span class="n">a2</span><span class="o">.</span><span class="n">addFilter</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
   <span class="n">a1</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">&#39;A debug message&#39;</span><span class="p">)</span>
   <span class="n">a1</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s">&#39;An info message with </span><span class="si">%s</span><span class="s">&#39;</span><span class="p">,</span> <span class="s">&#39;some parameters&#39;</span><span class="p">)</span>
   <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
       <span class="n">lvl</span> <span class="o">=</span> <span class="n">choice</span><span class="p">(</span><span class="n">levels</span><span class="p">)</span>
       <span class="n">lvlname</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLevelName</span><span class="p">(</span><span class="n">lvl</span><span class="p">)</span>
       <span class="n">a2</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">lvl</span><span class="p">,</span> <span class="s">&#39;A message at </span><span class="si">%s</span><span class="s"> level with </span><span class="si">%d</span><span class="s"> </span><span class="si">%s</span><span class="s">&#39;</span><span class="p">,</span> <span class="n">lvlname</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s">&#39;parameters&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>which, when run, produces something like:</p>
<div class="highlight-python"><pre>2010-09-06 22:38:15,292 a.b.c DEBUG    IP: 123.231.231.123 User: fred     A debug message
2010-09-06 22:38:15,300 a.b.c INFO     IP: 192.168.0.1     User: sheila   An info message with some parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f ERROR    IP: 127.0.0.1       User: jim      A message at ERROR level with 2 parameters
2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 127.0.0.1       User: sheila   A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,300 d.e.f ERROR    IP: 123.231.231.123 User: fred     A message at ERROR level with 2 parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1     User: jim      A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 192.168.0.1     User: jim      A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f ERROR    IP: 127.0.0.1       User: sheila   A message at ERROR level with 2 parameters
2010-09-06 22:38:15,301 d.e.f DEBUG    IP: 123.231.231.123 User: fred     A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f INFO     IP: 123.231.231.123 User: fred     A message at INFO level with 2 parameters</pre>
</div>
</div>
</div>
<div class="section" id="logging-to-a-single-file-from-multiple-processes">
<span id="multiple-processes"></span><h2>Logging to a single file from multiple processes<a class="headerlink" href="#logging-to-a-single-file-from-multiple-processes" title="Permalink to this headline">¶</a></h2>
<p>Although logging is thread-safe, and logging to a single file from multiple
threads in a single process <em>is</em> supported, logging to a single file from
<em>multiple processes</em> is <em>not</em> supported, because there is no standard way to
serialize access to a single file across multiple processes in Python. If you
need to log to a single file from multiple processes, one way of doing this is
to have all the processes log to a <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><tt class="xref py py-class docutils literal"><span class="pre">SocketHandler</span></tt></a>, and have a
separate process which implements a socket server which reads from the socket
and logs to file. (If you prefer, you can dedicate one thread in one of the
existing processes to perform this function.)
<a class="reference internal" href="#network-logging"><em>This section</em></a> documents this approach in more detail and
includes a working socket receiver which can be used as a starting point for you
to adapt in your own applications.</p>
<p>If you are using a recent version of Python which includes the
<a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><tt class="xref py py-mod docutils literal"><span class="pre">multiprocessing</span></tt></a> module, you could write your own handler which uses the
<a class="reference internal" href="../library/multiprocessing.html#multiprocessing.Lock" title="multiprocessing.Lock"><tt class="xref py py-class docutils literal"><span class="pre">Lock</span></tt></a> class from this module to serialize access to the
file from your processes. The existing <a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><tt class="xref py py-class docutils literal"><span class="pre">FileHandler</span></tt></a> and subclasses do
not make use of <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><tt class="xref py py-mod docutils literal"><span class="pre">multiprocessing</span></tt></a> at present, though they may do so in the
future. Note that at present, the <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><tt class="xref py py-mod docutils literal"><span class="pre">multiprocessing</span></tt></a> module does not provide
working lock functionality on all platforms (see
<a class="reference external" href="http://bugs.python.org/issue3770">http://bugs.python.org/issue3770</a>).</p>
</div>
<div class="section" id="using-file-rotation">
<h2>Using file rotation<a class="headerlink" href="#using-file-rotation" title="Permalink to this headline">¶</a></h2>
<p>Sometimes you want to let a log file grow to a certain size, then open a new
file and log to that. You may want to keep a certain number of these files, and
when that many files have been created, rotate the files so that the number of
files and the size of the files both remain bounded. For this usage pattern, the
logging package provides a <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><tt class="xref py py-class docutils literal"><span class="pre">RotatingFileHandler</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">glob</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.handlers</span>

<span class="n">LOG_FILENAME</span> <span class="o">=</span> <span class="s">&#39;logging_rotatingfile_example.out&#39;</span>

<span class="c"># Set up a specific logger with our desired output level</span>
<span class="n">my_logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;MyLogger&#39;</span><span class="p">)</span>
<span class="n">my_logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>

<span class="c"># Add the log message handler to the logger</span>
<span class="n">handler</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">RotatingFileHandler</span><span class="p">(</span>
              <span class="n">LOG_FILENAME</span><span class="p">,</span> <span class="n">maxBytes</span><span class="o">=</span><span class="mi">20</span><span class="p">,</span> <span class="n">backupCount</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>

<span class="n">my_logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">handler</span><span class="p">)</span>

<span class="c"># Log some messages</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">20</span><span class="p">):</span>
    <span class="n">my_logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">&#39;i = </span><span class="si">%d</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span>

<span class="c"># See what files are created</span>
<span class="n">logfiles</span> <span class="o">=</span> <span class="n">glob</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s">&#39;</span><span class="si">%s</span><span class="s">*&#39;</span> <span class="o">%</span> <span class="n">LOG_FILENAME</span><span class="p">)</span>

<span class="k">for</span> <span class="n">filename</span> <span class="ow">in</span> <span class="n">logfiles</span><span class="p">:</span>
    <span class="k">print</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
</pre></div>
</div>
<p>The result should be 6 separate files, each with part of the log history for the
application:</p>
<div class="highlight-python"><pre>logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5</pre>
</div>
<p>The most current file is always <tt class="file docutils literal"><span class="pre">logging_rotatingfile_example.out</span></tt>,
and each time it reaches the size limit it is renamed with the suffix
<tt class="docutils literal"><span class="pre">.1</span></tt>. Each of the existing backup files is renamed to increment the suffix
(<tt class="docutils literal"><span class="pre">.1</span></tt> becomes <tt class="docutils literal"><span class="pre">.2</span></tt>, etc.)  and the <tt class="docutils literal"><span class="pre">.6</span></tt> file is erased.</p>
<p>Obviously this example sets the log length much too small as an extreme
example.  You would want to set <em>maxBytes</em> to an appropriate value.</p>
</div>
<div class="section" id="an-example-dictionary-based-configuration">
<h2>An example dictionary-based configuration<a class="headerlink" href="#an-example-dictionary-based-configuration" title="Permalink to this headline">¶</a></h2>
<p>Below is an example of a logging configuration dictionary - it&#8217;s taken from
the <a class="reference external" href="https://docs.djangoproject.com/en/1.3/topics/logging/#configuring-logging">documentation on the Django project</a>.
This dictionary is passed to <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a> to put the configuration into effect:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">LOGGING</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s">&#39;version&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s">&#39;disable_existing_loggers&#39;</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
    <span class="s">&#39;formatters&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;verbose&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;format&#39;</span><span class="p">:</span> <span class="s">&#39;</span><span class="si">%(levelname)s</span><span class="s"> </span><span class="si">%(asctime)s</span><span class="s"> </span><span class="si">%(module)s</span><span class="s"> </span><span class="si">%(process)d</span><span class="s"> </span><span class="si">%(thread)d</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">&#39;</span>
        <span class="p">},</span>
        <span class="s">&#39;simple&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;format&#39;</span><span class="p">:</span> <span class="s">&#39;</span><span class="si">%(levelname)s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">&#39;</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s">&#39;filters&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;special&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;()&#39;</span><span class="p">:</span> <span class="s">&#39;project.logging.SpecialFilter&#39;</span><span class="p">,</span>
            <span class="s">&#39;foo&#39;</span><span class="p">:</span> <span class="s">&#39;bar&#39;</span><span class="p">,</span>
        <span class="p">}</span>
    <span class="p">},</span>
    <span class="s">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;null&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;level&#39;</span><span class="p">:</span><span class="s">&#39;DEBUG&#39;</span><span class="p">,</span>
            <span class="s">&#39;class&#39;</span><span class="p">:</span><span class="s">&#39;django.utils.log.NullHandler&#39;</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="s">&#39;console&#39;</span><span class="p">:{</span>
            <span class="s">&#39;level&#39;</span><span class="p">:</span><span class="s">&#39;DEBUG&#39;</span><span class="p">,</span>
            <span class="s">&#39;class&#39;</span><span class="p">:</span><span class="s">&#39;logging.StreamHandler&#39;</span><span class="p">,</span>
            <span class="s">&#39;formatter&#39;</span><span class="p">:</span> <span class="s">&#39;simple&#39;</span>
        <span class="p">},</span>
        <span class="s">&#39;mail_admins&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;level&#39;</span><span class="p">:</span> <span class="s">&#39;ERROR&#39;</span><span class="p">,</span>
            <span class="s">&#39;class&#39;</span><span class="p">:</span> <span class="s">&#39;django.utils.log.AdminEmailHandler&#39;</span><span class="p">,</span>
            <span class="s">&#39;filters&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;special&#39;</span><span class="p">]</span>
        <span class="p">}</span>
    <span class="p">},</span>
    <span class="s">&#39;loggers&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;django&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;handlers&#39;</span><span class="p">:[</span><span class="s">&#39;null&#39;</span><span class="p">],</span>
            <span class="s">&#39;propagate&#39;</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
            <span class="s">&#39;level&#39;</span><span class="p">:</span><span class="s">&#39;INFO&#39;</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="s">&#39;django.request&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;mail_admins&#39;</span><span class="p">],</span>
            <span class="s">&#39;level&#39;</span><span class="p">:</span> <span class="s">&#39;ERROR&#39;</span><span class="p">,</span>
            <span class="s">&#39;propagate&#39;</span><span class="p">:</span> <span class="bp">False</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="s">&#39;myproject.custom&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;console&#39;</span><span class="p">,</span> <span class="s">&#39;mail_admins&#39;</span><span class="p">],</span>
            <span class="s">&#39;level&#39;</span><span class="p">:</span> <span class="s">&#39;INFO&#39;</span><span class="p">,</span>
            <span class="s">&#39;filters&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;special&#39;</span><span class="p">]</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>For more information about this configuration, you can see the <a class="reference external" href="https://docs.djangoproject.com/en/1.6/topics/logging/#configuring-logging">relevant
section</a>
of the Django documentation.</p>
</div>
<div class="section" id="inserting-a-bom-into-messages-sent-to-a-sysloghandler">
<h2>Inserting a BOM into messages sent to a SysLogHandler<a class="headerlink" href="#inserting-a-bom-into-messages-sent-to-a-sysloghandler" title="Permalink to this headline">¶</a></h2>
<p><a class="reference external" href="http://tools.ietf.org/html/rfc5424">RFC 5424</a> requires that a
Unicode message be sent to a syslog daemon as a set of bytes which have the
following structure: an optional pure-ASCII component, followed by a UTF-8 Byte
Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the <a class="reference external" href="http://tools.ietf.org/html/rfc5424#section-6">relevant
section of the specification</a>.)</p>
<p>In Python 2.6 and 2.7, code was added to
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><tt class="xref py py-class docutils literal"><span class="pre">SysLogHandler</span></tt></a> to insert a BOM into the message, but
unfortunately, it was implemented incorrectly, with the BOM appearing at the
beginning of the message and hence not allowing any pure-ASCII component to
appear before it.</p>
<p>As this behaviour is broken, the incorrect BOM insertion code is being removed
from Python 2.7.4 and later. However, it is not being replaced, and if you
want to produce RFC 5424-compliant messages which include a BOM, an optional
pure-ASCII sequence before it and arbitrary Unicode after it, encoded using
UTF-8, then you need to do the following:</p>
<ol class="arabic">
<li><p class="first">Attach a <a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><tt class="xref py py-class docutils literal"><span class="pre">Formatter</span></tt></a> instance to your
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><tt class="xref py py-class docutils literal"><span class="pre">SysLogHandler</span></tt></a> instance, with a format string
such as:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="s">u&#39;ASCII section</span><span class="se">\ufeff</span><span class="s">Unicode section&#39;</span>
</pre></div>
</div>
<p>The Unicode code point <tt class="docutils literal"><span class="pre">u'\ufeff'</span></tt>, when encoded using UTF-8, will be
encoded as a UTF-8 BOM &#8211; the byte-string <tt class="docutils literal"><span class="pre">'\xef\xbb\xbf'</span></tt>.</p>
</li>
<li><p class="first">Replace the ASCII section with whatever placeholders you like, but make sure
that the data that appears in there after substitution is always ASCII (that
way, it will remain unchanged after UTF-8 encoding).</p>
</li>
<li><p class="first">Replace the Unicode section with whatever placeholders you like; if the data
which appears there after substitution contains characters outside the ASCII
range, that&#8217;s fine &#8211; it will be encoded using UTF-8.</p>
</li>
</ol>
<p>If the formatted message is Unicode, it <em>will</em> be encoded using UTF-8 encoding
by <tt class="docutils literal"><span class="pre">SysLogHandler</span></tt>. If you follow the above rules, you should be able to
produce RFC 5424-compliant messages. If you don&#8217;t, logging may not complain,
but your messages will not be RFC 5424-compliant, and your syslog daemon may
complain.</p>
</div>
<div class="section" id="implementing-structured-logging">
<h2>Implementing structured logging<a class="headerlink" href="#implementing-structured-logging" title="Permalink to this headline">¶</a></h2>
<p>Although most logging messages are intended for reading by humans, and thus not
readily machine-parseable, there might be cirumstances where you want to output
messages in a structured format which <em>is</em> capable of being parsed by a program
(without needing complex regular expressions to parse the log message). This is
straightforward to achieve using the logging package. There are a number of
ways in which this could be achieved, but the following is a simple approach
which uses JSON to serialise the event in a machine-parseable manner:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">json</span>
<span class="kn">import</span> <span class="nn">logging</span>

<span class="k">class</span> <span class="nc">StructuredMessage</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">message</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">message</span> <span class="o">=</span> <span class="n">message</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span> <span class="o">=</span> <span class="n">kwargs</span>

    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="s">&#39;</span><span class="si">%s</span><span class="s"> &gt;&gt;&gt; </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">message</span><span class="p">,</span> <span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span><span class="p">))</span>

<span class="n">_</span> <span class="o">=</span> <span class="n">StructuredMessage</span>   <span class="c"># optional, to improve readability</span>

<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">,</span> <span class="n">format</span><span class="o">=</span><span class="s">&#39;</span><span class="si">%(message)s</span><span class="s">&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="n">_</span><span class="p">(</span><span class="s">&#39;message 1&#39;</span><span class="p">,</span> <span class="n">foo</span><span class="o">=</span><span class="s">&#39;bar&#39;</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="s">&#39;baz&#39;</span><span class="p">,</span> <span class="n">num</span><span class="o">=</span><span class="mi">123</span><span class="p">,</span> <span class="n">fnum</span><span class="o">=</span><span class="mf">123.456</span><span class="p">))</span>
</pre></div>
</div>
<p>If the above script is run, it prints:</p>
<div class="highlight-python"><pre>message 1 &gt;&gt;&gt; {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"}</pre>
</div>
<p>Note that the order of items might be different according to the version of
Python used.</p>
<p>If you need more specialised processing, you can use a custom JSON encoder,
as in the following complete example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">unicode_literals</span>

<span class="kn">import</span> <span class="nn">json</span>
<span class="kn">import</span> <span class="nn">logging</span>

<span class="c"># This next bit is to ensure the script runs unchanged on 2.x and 3.x</span>
<span class="k">try</span><span class="p">:</span>
    <span class="nb">unicode</span>
<span class="k">except</span> <span class="ne">NameError</span><span class="p">:</span>
    <span class="nb">unicode</span> <span class="o">=</span> <span class="nb">str</span>

<span class="k">class</span> <span class="nc">Encoder</span><span class="p">(</span><span class="n">json</span><span class="o">.</span><span class="n">JSONEncoder</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">default</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">o</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">o</span><span class="p">,</span> <span class="nb">set</span><span class="p">):</span>
            <span class="k">return</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">o</span><span class="p">)</span>
        <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">o</span><span class="p">,</span> <span class="nb">unicode</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">o</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s">&#39;unicode_escape&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s">&#39;ascii&#39;</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">Encoder</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">default</span><span class="p">(</span><span class="n">o</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">StructuredMessage</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">message</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">message</span> <span class="o">=</span> <span class="n">message</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span> <span class="o">=</span> <span class="n">kwargs</span>

    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">Encoder</span><span class="p">()</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="k">return</span> <span class="s">&#39;</span><span class="si">%s</span><span class="s"> &gt;&gt;&gt; </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">message</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>

<span class="n">_</span> <span class="o">=</span> <span class="n">StructuredMessage</span>   <span class="c"># optional, to improve readability</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">,</span> <span class="n">format</span><span class="o">=</span><span class="s">&#39;</span><span class="si">%(message)s</span><span class="s">&#39;</span><span class="p">)</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="n">_</span><span class="p">(</span><span class="s">&#39;message 1&#39;</span><span class="p">,</span> <span class="n">set_value</span><span class="o">=</span><span class="nb">set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]),</span> <span class="n">snowman</span><span class="o">=</span><span class="s">&#39;</span><span class="se">\u2603</span><span class="s">&#39;</span><span class="p">))</span>

<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>When the above script is run, it prints:</p>
<div class="highlight-python"><pre>message 1 &gt;&gt;&gt; {"snowman": "\u2603", "set_value": [1, 2, 3]}</pre>
</div>
<p>Note that the order of items might be different according to the version of
Python used.</p>
</div>
<div class="section" id="customizing-handlers-with-dictconfig">
<span id="custom-handlers"></span><h2>Customizing handlers with <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a><a class="headerlink" href="#customizing-handlers-with-dictconfig" title="Permalink to this headline">¶</a></h2>
<p>There are times when you want to customize logging handlers in particular ways,
and if you use <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a> you may be able to do this without
subclassing. As an example, consider that you may want to set the ownership of a
log file. On POSIX, this is easily done using <tt class="xref py py-func docutils literal"><span class="pre">shutil.chown()</span></tt>, but the file
handlers in the stdlib don&#8217;t offer built-in support. You can customize handler
creation using a plain function such as:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">owned_file_handler</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">mode</span><span class="o">=</span><span class="s">&#39;a&#39;</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">owner</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">owner</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span>
            <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="s">&#39;a&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="n">shutil</span><span class="o">.</span><span class="n">chown</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="o">*</span><span class="n">owner</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">mode</span><span class="p">,</span> <span class="n">encoding</span><span class="p">)</span>
</pre></div>
</div>
<p>You can then specify, in a logging configuration passed to <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a>,
that a logging handler be created by calling this function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">LOGGING</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s">&#39;version&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s">&#39;disable_existing_loggers&#39;</span><span class="p">:</span> <span class="bp">False</span><span class="p">,</span>
    <span class="s">&#39;formatters&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;format&#39;</span><span class="p">:</span> <span class="s">&#39;</span><span class="si">%(asctime)s</span><span class="s"> </span><span class="si">%(levelname)s</span><span class="s"> </span><span class="si">%(name)s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">&#39;</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;file&#39;</span><span class="p">:{</span>
            <span class="c"># The values below are popped from this dictionary and</span>
            <span class="c"># used to create the handler, set the handler&#39;s level and</span>
            <span class="c"># its formatter.</span>
            <span class="s">&#39;()&#39;</span><span class="p">:</span> <span class="n">owned_file_handler</span><span class="p">,</span>
            <span class="s">&#39;level&#39;</span><span class="p">:</span><span class="s">&#39;DEBUG&#39;</span><span class="p">,</span>
            <span class="s">&#39;formatter&#39;</span><span class="p">:</span> <span class="s">&#39;default&#39;</span><span class="p">,</span>
            <span class="c"># The values below are passed to the handler creator callable</span>
            <span class="c"># as keyword arguments.</span>
            <span class="s">&#39;owner&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;pulse&#39;</span><span class="p">,</span> <span class="s">&#39;pulse&#39;</span><span class="p">],</span>
            <span class="s">&#39;filename&#39;</span><span class="p">:</span> <span class="s">&#39;chowntest.log&#39;</span><span class="p">,</span>
            <span class="s">&#39;mode&#39;</span><span class="p">:</span> <span class="s">&#39;w&#39;</span><span class="p">,</span>
            <span class="s">&#39;encoding&#39;</span><span class="p">:</span> <span class="s">&#39;utf-8&#39;</span><span class="p">,</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s">&#39;root&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;file&#39;</span><span class="p">],</span>
        <span class="s">&#39;level&#39;</span><span class="p">:</span> <span class="s">&#39;DEBUG&#39;</span><span class="p">,</span>
    <span class="p">},</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In this example I am setting the ownership using the <tt class="docutils literal"><span class="pre">pulse</span></tt> user and group,
just for the purposes of illustration. Putting it together into a working
script, <tt class="docutils literal"><span class="pre">chowntest.py</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span><span class="o">,</span> <span class="nn">logging.config</span><span class="o">,</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">shutil</span>

<span class="k">def</span> <span class="nf">owned_file_handler</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">mode</span><span class="o">=</span><span class="s">&#39;a&#39;</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">owner</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">owner</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span>
            <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="s">&#39;a&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="n">shutil</span><span class="o">.</span><span class="n">chown</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="o">*</span><span class="n">owner</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">mode</span><span class="p">,</span> <span class="n">encoding</span><span class="p">)</span>

<span class="n">LOGGING</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s">&#39;version&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s">&#39;disable_existing_loggers&#39;</span><span class="p">:</span> <span class="bp">False</span><span class="p">,</span>
    <span class="s">&#39;formatters&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;format&#39;</span><span class="p">:</span> <span class="s">&#39;</span><span class="si">%(asctime)s</span><span class="s"> </span><span class="si">%(levelname)s</span><span class="s"> </span><span class="si">%(name)s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">&#39;</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;file&#39;</span><span class="p">:{</span>
            <span class="c"># The values below are popped from this dictionary and</span>
            <span class="c"># used to create the handler, set the handler&#39;s level and</span>
            <span class="c"># its formatter.</span>
            <span class="s">&#39;()&#39;</span><span class="p">:</span> <span class="n">owned_file_handler</span><span class="p">,</span>
            <span class="s">&#39;level&#39;</span><span class="p">:</span><span class="s">&#39;DEBUG&#39;</span><span class="p">,</span>
            <span class="s">&#39;formatter&#39;</span><span class="p">:</span> <span class="s">&#39;default&#39;</span><span class="p">,</span>
            <span class="c"># The values below are passed to the handler creator callable</span>
            <span class="c"># as keyword arguments.</span>
            <span class="s">&#39;owner&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;pulse&#39;</span><span class="p">,</span> <span class="s">&#39;pulse&#39;</span><span class="p">],</span>
            <span class="s">&#39;filename&#39;</span><span class="p">:</span> <span class="s">&#39;chowntest.log&#39;</span><span class="p">,</span>
            <span class="s">&#39;mode&#39;</span><span class="p">:</span> <span class="s">&#39;w&#39;</span><span class="p">,</span>
            <span class="s">&#39;encoding&#39;</span><span class="p">:</span> <span class="s">&#39;utf-8&#39;</span><span class="p">,</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s">&#39;root&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;file&#39;</span><span class="p">],</span>
        <span class="s">&#39;level&#39;</span><span class="p">:</span> <span class="s">&#39;DEBUG&#39;</span><span class="p">,</span>
    <span class="p">},</span>
<span class="p">}</span>

<span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">dictConfig</span><span class="p">(</span><span class="n">LOGGING</span><span class="p">)</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s">&#39;mylogger&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">&#39;A debug message&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>To run this, you will probably need to run as <tt class="docutils literal"><span class="pre">root</span></tt>:</p>
<div class="highlight-python"><pre>$ sudo python3.3 chowntest.py
$ cat chowntest.log
2013-11-05 09:34:51,128 DEBUG mylogger A debug message
$ ls -l chowntest.log
-rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log</pre>
</div>
<p>Note that this example uses Python 3.3 because that&#8217;s where <tt class="xref py py-func docutils literal"><span class="pre">shutil.chown()</span></tt>
makes an appearance. This approach should work with any Python version that
supports <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a> - namely, Python 2.7, 3.2 or later. With pre-3.3
versions, you would need to implement the actual ownership change using e.g.
<a class="reference internal" href="../library/os.html#os.chown" title="os.chown"><tt class="xref py py-func docutils literal"><span class="pre">os.chown()</span></tt></a>.</p>
<p>In practice, the handler-creating function may be in a utility module somewhere
in your project. Instead of the line in the configuration:</p>
<div class="highlight-python"><pre>'()': owned_file_handler,</pre>
</div>
<p>you could use e.g.:</p>
<div class="highlight-python"><pre>'()': 'ext://project.util.owned_file_handler',</pre>
</div>
<p>where <tt class="docutils literal"><span class="pre">project.util</span></tt> can be replaced with the actual name of the package
where the function resides. In the above working script, using
<tt class="docutils literal"><span class="pre">'ext://__main__.owned_file_handler'</span></tt> should work. Here, the actual callable
is resolved by <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a> from the <tt class="docutils literal"><span class="pre">ext://</span></tt> specification.</p>
<p>This example hopefully also points the way to how you could implement other
types of file change - e.g. setting specific POSIX permission bits - in the
same way, using <a class="reference internal" href="../library/os.html#os.chmod" title="os.chmod"><tt class="xref py py-func docutils literal"><span class="pre">os.chmod()</span></tt></a>.</p>
<p>Of course, the approach could also be extended to types of handler other than a
<a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><tt class="xref py py-class docutils literal"><span class="pre">FileHandler</span></tt></a> - for example, one of the rotating file handlers,
or a different type of handler altogether.</p>
</div>
<div class="section" id="configuring-filters-with-dictconfig">
<span id="filters-dictconfig"></span><h2>Configuring filters with <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a><a class="headerlink" href="#configuring-filters-with-dictconfig" title="Permalink to this headline">¶</a></h2>
<p>You <em>can</em> configure filters using <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><tt class="xref py py-func docutils literal"><span class="pre">dictConfig()</span></tt></a>, though it
might not be obvious at first glance how to do it (hence this recipe). Since
<a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><tt class="xref py py-class docutils literal"><span class="pre">Filter</span></tt></a> is the only filter class included in the standard
library, and it is unlikely to cater to many requirements (it&#8217;s only there as a
base class), you will typically need to define your own <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><tt class="xref py py-class docutils literal"><span class="pre">Filter</span></tt></a>
subclass with an overridden <a class="reference internal" href="../library/logging.html#logging.Filter.filter" title="logging.Filter.filter"><tt class="xref py py-meth docutils literal"><span class="pre">filter()</span></tt></a> method. To do this,
specify the <tt class="docutils literal"><span class="pre">()</span></tt> key in the configuration dictionary for the filter,
specifying a callable which will be used to create the filter (a class is the
most obvious, but you can provide any callable which returns a
<a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><tt class="xref py py-class docutils literal"><span class="pre">Filter</span></tt></a> instance). Here is a complete example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.config</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="k">class</span> <span class="nc">MyFilter</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">Filter</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">param</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">param</span> <span class="o">=</span> <span class="n">param</span>

    <span class="k">def</span> <span class="nf">filter</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">record</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">param</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
            <span class="n">allow</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">allow</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">param</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">record</span><span class="o">.</span><span class="n">msg</span>
        <span class="k">if</span> <span class="n">allow</span><span class="p">:</span>
            <span class="n">record</span><span class="o">.</span><span class="n">msg</span> <span class="o">=</span> <span class="s">&#39;changed: &#39;</span> <span class="o">+</span> <span class="n">record</span><span class="o">.</span><span class="n">msg</span>
        <span class="k">return</span> <span class="n">allow</span>

<span class="n">LOGGING</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s">&#39;version&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s">&#39;filters&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;myfilter&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;()&#39;</span><span class="p">:</span> <span class="n">MyFilter</span><span class="p">,</span>
            <span class="s">&#39;param&#39;</span><span class="p">:</span> <span class="s">&#39;noshow&#39;</span><span class="p">,</span>
        <span class="p">}</span>
    <span class="p">},</span>
    <span class="s">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;console&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s">&#39;class&#39;</span><span class="p">:</span> <span class="s">&#39;logging.StreamHandler&#39;</span><span class="p">,</span>
            <span class="s">&#39;filters&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;myfilter&#39;</span><span class="p">]</span>
        <span class="p">}</span>
    <span class="p">},</span>
    <span class="s">&#39;root&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s">&#39;level&#39;</span><span class="p">:</span> <span class="s">&#39;DEBUG&#39;</span><span class="p">,</span>
        <span class="s">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s">&#39;console&#39;</span><span class="p">]</span>
    <span class="p">},</span>
<span class="p">}</span>

<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">dictConfig</span><span class="p">(</span><span class="n">LOGGING</span><span class="p">)</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">&#39;hello&#39;</span><span class="p">)</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s">&#39;hello - noshow&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This example shows how you can pass configuration data to the callable which
constructs the instance, in the form of keyword parameters. When run, the above
script will print:</p>
<div class="highlight-python"><pre>changed: hello</pre>
</div>
<p>which shows that the filter is working as configured.</p>
<p>A couple of extra points to note:</p>
<ul class="simple">
<li>If you can&#8217;t refer to the callable directly in the configuration (e.g. if it
lives in a different module, and you can&#8217;t import it directly where the
configuration dictionary is), you can use the form <tt class="docutils literal"><span class="pre">ext://...</span></tt> as described
in <a class="reference internal" href="../library/logging.config.html#logging-config-dict-externalobj"><em>Access to external objects</em></a>. For example, you could have used
the text <tt class="docutils literal"><span class="pre">'ext://__main__.MyFilter'</span></tt> instead of <tt class="docutils literal"><span class="pre">MyFilter</span></tt> in the above
example.</li>
<li>As well as for filters, this technique can also be used to configure custom
handlers and formatters. See <a class="reference internal" href="../library/logging.config.html#logging-config-dict-userdef"><em>User-defined objects</em></a> for more
information on how logging supports using user-defined objects in its
configuration, and see the other cookbook recipe <a class="reference internal" href="#custom-handlers"><em>Customizing handlers with dictConfig()</em></a> above.</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Logging Cookbook</a><ul>
<li><a class="reference internal" href="#using-logging-in-multiple-modules">Using logging in multiple modules</a></li>
<li><a class="reference internal" href="#multiple-handlers-and-formatters">Multiple handlers and formatters</a></li>
<li><a class="reference internal" href="#logging-to-multiple-destinations">Logging to multiple destinations</a></li>
<li><a class="reference internal" href="#configuration-server-example">Configuration server example</a></li>
<li><a class="reference internal" href="#sending-and-receiving-logging-events-across-a-network">Sending and receiving logging events across a network</a></li>
<li><a class="reference internal" href="#adding-contextual-information-to-your-logging-output">Adding contextual information to your logging output</a><ul>
<li><a class="reference internal" href="#using-loggeradapters-to-impart-contextual-information">Using LoggerAdapters to impart contextual information</a><ul>
<li><a class="reference internal" href="#using-objects-other-than-dicts-to-pass-contextual-information">Using objects other than dicts to pass contextual information</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-filters-to-impart-contextual-information">Using Filters to impart contextual information</a></li>
</ul>
</li>
<li><a class="reference internal" href="#logging-to-a-single-file-from-multiple-processes">Logging to a single file from multiple processes</a></li>
<li><a class="reference internal" href="#using-file-rotation">Using file rotation</a></li>
<li><a class="reference internal" href="#an-example-dictionary-based-configuration">An example dictionary-based configuration</a></li>
<li><a class="reference internal" href="#inserting-a-bom-into-messages-sent-to-a-sysloghandler">Inserting a BOM into messages sent to a SysLogHandler</a></li>
<li><a class="reference internal" href="#implementing-structured-logging">Implementing structured logging</a></li>
<li><a class="reference internal" href="#customizing-handlers-with-dictconfig">Customizing handlers with <tt class="docutils literal"><span class="pre">dictConfig()</span></tt></a></li>
<li><a class="reference internal" href="#configuring-filters-with-dictconfig">Configuring filters with <tt class="docutils literal"><span class="pre">dictConfig()</span></tt></a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="logging.html"
                        title="previous chapter">Logging HOWTO</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="regex.html"
                        title="next chapter">Regular Expression HOWTO</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/howto/logging-cookbook.txt"
         rel="nofollow">Show Source</a></li>
</ul>

<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="regex.html" title="Regular Expression HOWTO"
             >next</a> |</li>
        <li class="right" >
          <a href="logging.html" title="Logging HOWTO"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="http://www.python.org/">Python</a> &raquo;</li>
        <li>
          <a href="../index.html">Python v2.7.8 documentation</a> &raquo;
        </li>

          <li><a href="index.html" >Python HOWTOs</a> &raquo;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2014, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Jun 29, 2014.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.7.
    </div>

  </body>
</html>